export function createStore(reducer, fn) {
  let state;
  let callbacks = [];
  function getState() {
    return state
  }
  function dispatch(action) {
    state = reducer(state, action)
    console.log(callbacks)
    callbacks.forEach(f => {
      f()
    })
  }
  dispatch({ type: "@@type.0.032.304.4" })
  function subscribe(f) {
    callbacks.push(f)
    return function () {
      callbacks = callbacks.filter(v => v != f)
    }
  }

  if (typeof fn == 'function') {
    let newCreateStore = fn(createStore)
    return newCreateStore(reducer)
  }

  return {
    getState, dispatch, subscribe
  }
}

export function combineReducers(obj) {
  return function rootReducer(rootState, action) {
    /* 
    rootState:{
      QQQ:{count:100,name:"珠峰"},
      WWW:{color:'red'}
    }
    */
    rootState = rootState || {}
    Object.keys(obj).forEach(key => {
      rootState[key] = obj[key](rootState[key], action)
    })
    return rootState
  }
}
export function compose(...fs) {
  //     fs [a,b]
  let first = fs.shift()
  return function c(...arg) {
    // debugger
    return fs.reduce((prev, cur) => {
      return cur(prev)
    }, first(...arg))
  }

}
export function applyMiddleware(...middles) {
  // middle  -->  thunk
  return function fn(createStore) {
    return function newCreateStore(reducer) {
      let store = createStore(reducer)
      let temps = middles.map(middle => middle(store))
      let _dispatch = compose(...temps)(store.dispatch)
      // debugger
      return {
        ...store,
        dispatch: _dispatch
      }
    }
  }
}